//
//  SpeechHandler.swift
//  DentalFormula
//
//  Created by AMalashin on 27.09.2023.
//

import Foundation

struct TextDecoder {
    static func decode(text: String, languageId: String) -> [Tooth] {
        let parts = text // split input string for tooth parts -> make parts array (each element = tooth description)
                      .lowercased()
                      .components(separatedBy: String(localized: "decoder.tooth.separator"))
                      .filter { !$0.isEmpty }
        let clearedParts = parts.map { // split each part for getting tooth info -> make array of arrays
            $0.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: CharacterSet(charactersIn: " -"))
        }
        var teeth: [Tooth] = [] // resulting tooth array

        for part in clearedParts {
            var toothNumber: Int = 0
            var toothCondition: ToothCondition?
            for comp in part {
                if let num = Int(comp) { toothNumber = num; continue }

                if toothCondition != nil && comp == String(localized: "decoder.defect.filling") { toothCondition = .decayFilling; continue }
                if toothCondition == nil && comp == String(localized: "decoder.defect.filling") { toothCondition = .filling }
                if toothCondition == nil && comp == String(localized: "decoder.defect.decay")   { toothCondition = .decay }
                if toothCondition != nil && comp == String(localized: "decoder.defect.decay")   { toothCondition = .decayFilling; continue }
                if toothCondition == nil && comp == String(localized: "decoder.defect.missed")  { toothCondition = .missed; continue }
                if toothCondition == nil && comp == String(localized: "decoder.defect.intact")  { toothCondition = .intact; continue }
//                if toothCondition == nil && comp == "удален" { toothCondition = .missed; continue }
            }
            if toothNumber != 0, let condition = toothCondition, let tooth = Tooth(number: toothNumber, condition: condition) {
                teeth.append( tooth )
            }
        }
        return teeth
    }
}
